/**
 * 专家研讨会统计图表
 */
"use strict";

// 获取新数据间隔 ms
var delay = 2000,

mapDelay = 1000,

// 评论列表框 可显示的数量
commentListNumber = 3,

// 红包列表框 可显示的数量
redpackListNumber = 6,

// 总访问量显示位数
pvCountLength = 8,

// http://192.168.1.17/redpack?target_id=6&lastid=11688&limit=10 红包
// http://192.168.1.17/comment?target_id=6&lastid=11688&limit=10 评论
// http://192.168.1.17/collect?target_id=6 汇总信息

baseURL = 'http://192.168.10.30/',

// 统计数据 汇总信息 数据URL
staticsDataURL = baseURL + 'collect?target_id=8',

// 评论 数据URL
commentDataURL = baseURL + 'comment?target_id=8',

// 红包 数据URL
redpackDataURL = baseURL + 'redpack?target_id=8',

//地图数据
mapDataURL = baseURL + 'mapinfo',

// 字体颜色
textColor = '#ffd37d',

//小字体颜色
smallTextColor = '#ccc',

// 折线颜色
lineColor = '#e96406',

// 边框颜色
borderColor = '#626262',

// 总访问量元素
allVisitTarget = $('.all-visit .num span');

// 去除HTML特殊符号
function htmlDecode(str) { 
    return str.replace(/&(\W|\w)+;/ig, '');
} 

/**********************************************
 * 评论数折线图
 *********************************************/
var commentLineOption = {
    textStyle: { color: smallTextColor },
    xAxis: {
        name: '时间',
        type: 'time',
        splitLine: { show: false }
    },
    yAxis: {
        name: '评论数量',
        type: 'value',
        splitLine: { show: false }
    },
    series: [{
        itemStyle: {
            normal: { color: lineColor }
        },
        type: 'line',
        showSymbol: false,
    }]
};

var commentLineChart = echarts.init($('.comment-line-charts')[0]),
    commentLineData = [];

commentLineChart.setOption(commentLineOption);

var commentAmountTarget = $('.comment-line-amount'); 
var updateCommentLineChart = function(data) {
    commentAmountTarget.text(data);

    var d = {
        value: [ 
            (new Date()).toString(),
            data
        ]
    };

    commentLineData.push(d);
    commentLineChart.setOption({
        series: [{ data: commentLineData }],
        yAxis: {
            max: parseInt(data * 1.5 / 100) * 100
        }
    });
};

/**********************************************
 * 评论 地图
 *********************************************/

 // 计算地图中点的尺寸
function mapSymbolSize(value) {
    var t = value / 100;
     // TODO 
    t = t > 15 ? 15 : t;
    t = t < 3 ? 3 : t;
    return t;
}

var commentMapOption = {
    geo: {
        map: 'china',
        label: { emphasis: { show: false } }, 
        roam: true,
        itemStyle: {
            normal: {areaColor: '#323c48', borderColor: '#111'}, 
            emphasis: {areaColor: '#2a333d'} 
        }
    },
    series : [{
        name: '评论',
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: function(val) {
            return mapSymbolSize(val[2]);
        },
        itemStyle: {normal: {color: '#ec4000'} } 
    }]
};

var commentMapChart = echarts.init($('.comment-map-charts')[0]),
    commentMapData = [];

commentMapChart.setOption(commentMapOption);
var updateCommentMapChart = function(data) { 
    var d = [];
    for(var i = 0; i < data.length; i++) {
        var tmp = data[i];

        for(var key in tmp) {
            var geoCoord = geoCoordMap[key];
            d.push({
                name: key,
                value: geoCoord.concat(tmp[key])
            });
        }
    }
    commentMapChart.setOption({
        series: [{ data: d }]
    });
};

/**********************************************
 * PV观看人数折线图
 *********************************************/
var pvLineOption = {
	textStyle: { color: smallTextColor },
    xAxis: {
        name: '时间',
        type: 'time',
        splitLine: { show: false }
    },
    yAxis: {
    	name: '观看人数',
        type: 'value',
        splitLine: { show: false },
    },
    series: [{
        itemStyle: {normal: { color: '#7300fe' } },
        type: 'line',
        showSymbol: false,
        areaStyle: {normal: {}},
    }]
};

var pvLineChart = echarts.init($('.pv-line-charts')[0]),
	pvLineData = [];

pvLineChart.setOption(pvLineOption);

var pvLineAmountTarget = $('.pv-line-amount');    
var updatePvLineChart = function(amount) {
    pvLineAmountTarget.text(amount);

    var d = {
        value: [ 
            (new Date()).toString(),
            amount
        ]
    };

    pvLineData.push(d);

    pvLineChart.setOption({
        series: [{ data: pvLineData }],
        yAxis: {
            max: parseInt(amount * 1.5 / 100) * 100
        }
    });
};

/**********************************************
 * PV 地图
 *********************************************/
var testMapOption = {
    tooltip: {},
    visualMap: {
        min: 0,
        max: 1500,
        left: 'right',
        top: 'bottom',
        //text: ['高','低'],
        seriesIndex: [1],
        inRange: {color: ['#abbfe5', '#0004a0'] },
        calculable : false
    },
    geo: {
        map: 'china',
        roam: true,
        label: {normal: {show: true, textStyle: {color: 'rgba(0,0,0,0.4)'} } },
        itemStyle: {
            normal:{borderColor: 'rgba(0, 0, 0, 0.2)'},
            emphasis:{areaColor: null, shadowOffsetX: 0, shadowOffsetY: 0, shadowBlur: 20, borderWidth: 0, shadowColor: 'rgba(0, 0, 0, 0.5)'}
        }
    },
    series : [
        {
           type: 'scatter',
           coordinateSystem: 'geo'
        },
        {
            name: 'categoryA',
            type: 'map',
            geoIndex: 0,
        }
    ]
};

var testMapChart = echarts.init($('.test-map-charts')[0]);

testMapChart.setOption(testMapOption);
var updateTestMapChart = function(data) {
    var d = [];

    for (var i = 0; i < data.length; i++) {
        for (var key in data[i]) {
            d.push({
                name: key, 
                value: data[i][key]
            })
        }
    }

    testMapChart.setOption({
        series: [{}, { data: d }]
    });
};

/**********************************************
 * 追加新评论
 *********************************************/
var addComment = function(comments) {
	// var comments = comments || [
	// 	{
 //         wechat_nickname: '河南.jw',
	// 		wechat_avatar: 'https://img6.bdstatic.com/img/image/smallpic/d.jpg',
	// 		content: randomString(Math.round(Math.random() * 20 + 3)),
	// 		comment_id: 1
	// 	}
	// ];
	
	var target = $('.comment-list ul');
	comments.forEach(function(item) {
  		var htmlElement = `<li class="list-group-item talker" data-id="` + item.comment_id + `">
                                <div class="media">
                                  <img class="d-flex align-self-start mr-3 rounded-circle" width="35" height="35" src="`+ item.wechat_avatar +`">
                                  <div class="media-body">
                                  <span class="talk-name  text-truncate">` + htmlDecode(item.wechat_nickname) + `</span>
                                    <p class=" span talk-size " style="margin: 0">`+ item.content +`</p>
                                  </div>
                                </div>
                            </li>`;

        // 先清除一个
        if (target.find('li').length >= commentListNumber)
        	target.find('li').last().remove();

        $('.comment-list ul').prepend(htmlElement);
	});
};

/**********************************************
 * 追加新红包
 *********************************************/
var addRedpack = function(redpacks) {
	// var redpacks = redpacks || [
	// 	{
	// 		wechat_nickname: 'Mr.jw',
	// 		wechat_avatar: 'https://img6.bdstatic.com/img/image/smallpic/d.jpg',
	// 		redpack_amount: (Math.random() * 100 + 1 ).toFixed(2),
	// 		address: '河南  郑州',
 //            redpack_id: 1
	// 	}
	// ];

	var target = $('.redpack-list ul');
    
	redpacks.forEach(function(item) { 
        // console.log(item.wechat_nickname)
		var htmlElement = `<li class="list-group-item justify-content-between red-package" data-id="` + item.redpack_id + `">
                    <span>
                        <img src="` + item.wechat_avatar + `" width="25" height="25" class="rounded-circle">
                        <span class="red-name  text-truncate">` + htmlDecode(item.wechat_nickname) + `</span> `;

                    if (item.type == 1) {
                        htmlElement += `<span class="take">抽中红包</span> <span class="money-color">￥`+ (item.amount / 100).toFixed(2) +`</span>`;
                    } else {
                        htmlElement += `<span class="take">抽中</span> <span class="money-color">￥`+ (item.amount / 100).toFixed(2) +`</span> 元提货券 `;
                    }
                    
                    htmlElement += `</span>
                    <span class="badge site ">`+ item.address +`</span>
                </li>`;

        // 先清除一个
        if (target.find('li').length >= redpackListNumber)
        	target.find('li').last().remove();

        $('.redpack-list ul').prepend(htmlElement);
	});
};

var updateStatics = function() {
    $.ajax({
        url: staticsDataURL,
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            var info = data.info;

            if (data.errcode == 0) {
                // 总访问量 ===========================================
                info.pvcount = info.pvcount || 1;
                var pvCount = info.pvcount.toString().split('') || [1];
                
                // 填充总访问量位数
                while(pvCount.length < pvCountLength) {
                    pvCount.unshift('0');
                }

                allVisitTarget.each(function(i) {
                    $(this).text(pvCount[i]);
                });

                // 评论数量============================================
                // 折线
                info.commentcurrent = (typeof info.commentcurrent == 'number') ? info.commentcurrent : 1;
                updateCommentLineChart(info.commentcurrent);

                // PV =================================================
                // 折线
                info.pvcurrent = (typeof info.pvcurrent == 'number') ? info.pvcurrent : 1;
                updatePvLineChart(info.pvcurrent);
            } 
        }, 
        error: function(msg) {
            console.warn(msg);
        }
    });
};
// 评论地图
var updateMapStatics = function() {
    $.ajax({
        url: mapDataURL,
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            var info = data.info;

            if (data.errcode == 0) {
                // 评论数量============================================
                // 地图
                (info.commentlist && info.commentlist.length > 0) && updateCommentMapChart(info.commentlist);

                // console.log(info.commentlist);
                // console.log(info.commentlist.length);

                // PV =================================================
                (info.pvlist && info.pvlist.length > 0) && updateTestMapChart(info.pvlist);
            } 
        }, 
        error: function(msg) {
            console.warn(msg);
        }
    });
};

var updateComment = function() {
    var lastId = $('.comment-list li').eq(0).data('id') || 0;

    $.ajax({
        url: commentDataURL,
        method: 'GET',
        dataType: 'json',
        data: {
            lastid: lastId,
            limit: 10
        },
        success: function(data) {
            var info = data.info;
            if (data.errcode == 0) {
                var length = info.length;

                var comments = [];
                for (var i = 0; i < length; i++) {
                    comments.push(JSON.parse(info[i]));
                }

                (comments.length > 0) && addComment(comments);
            }
        }, 
        error: function(msg) {
            console.warn(msg);
        }
    });
};

var updateRedpack = function() {
    var lastId = $('.redpack-list li').eq(0).data('id') || 0;

    $.ajax({
        url: redpackDataURL,
        method: 'GET',
        dataType: 'json',
        data: {
            lastid: lastId,
            limit: 10
        },
        success: function(data) {
            var info = data.info;
            if (data.errcode == 0) {
                var length = info.length;

                var redpacks = [];
                for (var i = 0; i < length; i++) {
                    redpacks.push(JSON.parse(info[i]));
                }

                (redpacks.length > 0) && addRedpack(redpacks);
            } 
        }, 
        error: function(msg) {
            console.warn(msg);
        }
    });
};

var updateInterval = setInterval(function() {
    updateStatics();

    updateComment();

    updateRedpack();
}, delay);

var updateMapInterval = setInterval(function() {
    updateMapStatics();
}, mapDelay);

var start = function() {
    updateInterval = setInterval(function() {
        updateStatics();

        updateComment();

        updateRedpack();
    }, delay);

    updateMapInterval = setInterval(function() {
        updateMapStatics();
    }, mapDelay);
}

var stop = function() {
    clearInterval(updateInterval);
    clearInterval(updateMapInterval);
};